<template>
  <div class="login-container">
    <div class="login-form">
      <div class="title-container">
        <h3 class="title">书城后台管理系统</h3>
      </div>
      
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" status-icon>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            type="text"
            tabindex="1"
            prefix-icon="i-ep-user"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="密码"
            :type="passwordVisible ? 'text' : 'password'"
            tabindex="2"
            prefix-icon="i-ep-lock"
            show-password
          />
        </el-form-item>
        
        <el-button :loading="loading" type="primary" size="default" @click="handleLogin" style="width: 100%; margin-bottom: 30px">
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminAPI } from '../../utils/api'
import { useUserStore } from '../../store'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)
const passwordVisible = ref(false)

const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用登录API
        const res = await adminAPI.login(loginForm)
        
        // 处理登录结果
        if (res.code === 200 && res.data) {
          // 保存token到store
          userStore.setToken(res.data.token)
          // 保存用户信息到store
          userStore.updateUser(res.data.userInfo)
          // 登录成功提示
          ElMessage.success('登录成功')
          // 跳转到首页
          router.push('/')
        } else {
          ElMessage.error(res.message || '登录失败')
        }
      } catch (error) {
        console.error('登录异常:', error)
        ElMessage.error('登录失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #2d3a4b;
}

.login-form {
  width: 400px;
  padding: 40px 35px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title-container {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 26px;
  color: #303133;
  margin: 0;
  font-weight: bold;
}
</style> 